require File.expand_path('../../config/environment',  __FILE__)

agent = Mechanize.new
agent.max_history = 1
agent.cookie_jar.load_cookiestxt(File.new("#{Rails.root}/tmp/cookie.txt"))

last_id = 0
while true
  shop_tasks = Shop.all(:conditions => "id > #{last_id} and user_id is not null and prom_url is null", :order => 'id ASC', :limit => 100)
  break if shop_tasks.blank?
  last_id = shop_tasks.last.id

  shop_tasks.each do |shop_task|
    page = agent.get shop_task.all_code_url
    unless (page.title =~ /阿里妈妈登录页面/).nil? #未登录或登陆过期
      Rails.logger.error "会话过期"
      exit
    end
    link_code = page.search("#J_getLinkCode")
    if link_code.present?
      shop_task.prom_url = link_code.text
      shop_task.save
    else
      Rails.logger.warn "解析推广出错,此用户没有推广或其它错误 #{shop_task.all_code_url}"
    end
  end
end
